package com.lixin.juc.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyCache {

    private final Map<String, Object> cache = new HashMap<>();
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void set(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "线程开始写入" + key);
            TimeUnit.SECONDS.sleep(1);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "线程写入完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        readWriteLock.readLock().lock();
        Object value = null;
        try {
            System.out.println(Thread.currentThread().getName() + "线程开始读取" + key);
            TimeUnit.SECONDS.sleep(1);
            value = cache.get(key);
            System.out.println(Thread.currentThread().getName() + "线程读取完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return value;
    }

}
